#INCLUDE "PROTHEUS.CH"
#INCLUDE "APWEBSRV.CH"
/*/{Protheus.doc} DTRWEBSR

@descricao Web Service de uso Dataroute

@author Peterson Scherwinski

@since 14/04/2014
/*/
WSSERVICE DTRWEBSR  DESCRIPTION "Webservice uso interno"

	//VARIAVEIS parametros de entrada nos metodos
	WSDATA TOKEN				AS String //USUARIO
	WSDATA UserName			AS String //USUARIO
	WSDATA UserPassword		AS String //Senha
	WSDATA DateStart			AS String
	WSDATA DateEnd			AS String
	WSDATA RESOURCE			AS String OPTIONAL
	WSDATA JOBUPDT			as DadosAgenda
	WSDATA CODRESOURSE		AS STRING

	//Variaveis de retorno dos metodos
	WSDATA USERDATAIL			as Array Of DadosLogin
	WSDATA RESOSCHED			as Array Of DadosAgenda
	WSDATA OSMESSAGE			as String OPTIONAL
	WSDATA RESUMOHS			as StruRESUMO

	//Declaracao dos Metodos

	//Metodo validacao do login/senha
	WSMETHOD GETLOGIN			DESCRIPTION "Validacao de Login de acesso"
	//Metodo para buscar as agendas
	WSMETHOD GETSCHEDULE			DESCRIPTION "Listagem das agendas"
	WSMETHOD PUTJOB				DESCRIPTION "Apontamento de Atividades"
	WSMETHOD DELJOB				DESCRIPTION "Excluir Apontamento de Atividades"
	WSMETHOD GETRESUMO			DESCRIPTION "Resumo de Horas"

ENDWSSERVICE

//
//Estruturas de dados
//

//dados do Login
WSStruct DadosLogin
	WSDATA USERNAME   	as String	optional
	WSDATA FULLNAME   	as String	optional
	WSDATA TPACCESS 		as Float	optional
	WSDATA CODRECUR 		as String	optional
	WSDATA SKIN 			as String	optional
	WSDATA AGENDA			as String	optional
EndWSStruct

//dados das agendas
WSStruct DadosAgenda
	WSDATA RESOURCE   	as String	optional
	WSDATA RESONAME   	as String	optional
	WSDATA SKIN   		as String	optional
	WSDATA CUSTOMER   	as String	optional
	WSDATA CUSTNAME   	as String	optional
	WSDATA PROJCODE   	as String	optional
	WSDATA PROJDESC   	as String	optional
	WSDATA PROJTASK   	as String	optional
	WSDATA TASKDESC   	as String	optional
	WSDATA DATESCHE 		as String	optional
	WSDATA TIMESTAR 		as String	optional
	WSDATA TIMEEND		as String	optional
	WSDATA TIMEDESC		as String	optional
	WSDATA DESCRIPT  		as String	optional
	WSDATA APTOREC  		as String	optional
	WSDATA VLRALMO 		as Float	optional
	WSDATA VLRDESP 		as Float	optional
	WSDATA OBSDESP  		as String	optional
	WSDATA OSGERADA  		as String	optional
	WSDATA AGERECNO  		as Float	optional
	WSDATA OSRECNO  		as Float	optional
EndWSStruct

WSStruct StruRESUMO
	WSData APTOS		As Array of ResumOS Optional
	WsData	nTotal		As Float Optional
endWSStruct

WSStruct ResumOS
	WSDATA DATA		   	as String	optional
	WSDATA PROJETO	   	as String	optional
	WSDATA TAREFA 		as String	optional
	WSDATA HORAINI 		as String	optional
	WSDATA HORAFIM		as String	optional
	WSDATA OUTROS			as String	optional
	WSDATA TOTAL			as String	optional
EndWSStruct
//
//Metodos
//

//validacao de usuario e senha
WSMETHOD GETLOGIN WSRECEIVE TOKEN,UserName,UserPassword WSSEND USERDATAIL WSSERVICE DTRWEBSR
	local lRet := .t.
	local TPAcesso	:= 1
	local oDadosLogin

	//VALIDA TOKEN PARA USO DO WS
	if !(::TOKEN = "DATAROUTEWEB")
		SetSoapFault("Acesso nao autorizado",;
			"Verifique os parametros informados.")
		return .F.
	endif

	dbSelectArea("AI3")
	AI3->(dbSetOrder(2))//FILIAL+USUARIO
	AI3->(dbSeek(xFilial("AI3")+::UserName))
	
	if alltrim(AI3->AI3_LOGIN)<>alltrim(::UserName).and.ALLTRIM(AI3->AI3_PSW)<>alltrim(::UserPassword)
		SetSoapFault("Acesso nao autorizado",;
			"Usuario ou senha invalidos")
		return .F.
	endif
	
	//AI4 - CLIENTE ASSOCIADO
	//SE TIVER CLIENTE ASSOCIADO
	//ACESSO DO CLIENTE
	//TPAcesso	:= 2
	
	//PREPARA RETORNO DOS DADOS
	
	//CARREGA DADOS DO LOGIN
	oDadosLogin := WSClassNew("DadosLogin")
	oDadosLogin:USERNAME	:= alltrim(AI3->AI3_LOGIN)
	oDadosLogin:FULLNAME	:= alltrim(AI3->AI3_NOME)
	oDadosLogin:TPACCESS	:= TPAcesso
	oDadosLogin:CODRECUR	:= alltrim(AI3->AI3_ZRECUR)
	oDadosLogin:SKIN		:= alltrim(AI3->AI3_SKIN)
	oDadosLogin:AGENDA	:= alltrim(AI3->AI3_ZAGEND)
	
	aAdd(::USERDATAIL,oDadosLogin)
return(lRet)

//METODO PARA CARREGAR AS AGENDAS
WSMETHOD GETSCHEDULE WSRECEIVE TOKEN,RESOURCE,DateStart, DateEnd WSSEND RESOSCHED WSSERVICE DTRWEBSR
	local lRet := .t.
	local oDadosAgenda
	local cQuery := ""

	//VALIDA TOKEN PARA USO DO WS
	if !(::TOKEN = "DATAROUTEWEB")
		SetSoapFault("Acesso nao autorizado",;
			"Verifique os parametros informados.")
		return .F.
	endif

	cQuery := "Select "
	cQuery += "AE8_DESCRI "
	cQuery += ",ZN0_RECURS, ZN0_PROJET, ZN0_TAREFA, ZN0_DATA, ZN0_HORAI, ZN0_HORAF, ZN0_GERADA, ZN0_OUTROS , ZN0.R_E_C_N_O_ ZN0_RECNO, ZN0_RECNOS "
	cQuery += ",AF9_DESCRI ,AF8_DESCRI, AF8_CLIENT, AF8_LOJA "
	cQuery += ",A1_NREDUZ "
	cQuery += "from "+retSqlTab("AE8")+" "
	cQuery += "Left Join "+retSqlTab("ZN0")+" on (ZN0_FILIAL = '"+xFilial("ZN0")+"' and AE8_RECURS = ZN0_RECURS and ZN0_DATA between '"+::DateStart+"' and '"+::DateEnd+"' and ZN0.D_E_L_E_T_ = ' ') "
	//cQuery += "Left Join "+retSqlTab("AF8")+" on (AF8_FILIAL = '"+xFilial("AF8")+"' and AF8_PROJET = ZN0_PROJET AND AF8.D_E_L_E_T_ = ' ') "
	cQuery += "Left Join "+retSqlName("AF8")+" AF8 on (AF8_FILIAL = '"+xFilial("AF8")+"' and AF8_PROJET = ZN0_PROJET AND AF8.D_E_L_E_T_ = ' ' AND AF8_REVISA = (select MAX(AF8_REVISA) from "+retSqlName("AF8")+" AF8B where AF8B.AF8_PROJET = AF8.AF8_PROJET AND AF8B.D_E_L_E_T_ = '')) "
	cQuery += "Left Join "+retSqlTab("AF9")+" on (AF9_FILIAL = '"+xFilial("AF9")+"' and AF9_PROJET = ZN0_PROJET and AF9_TAREFA = ZN0_TAREFA AND AF9_REVISA = AF8_REVISA AND AF9.D_E_L_E_T_ = ' ') "
	cQuery += "Left Join "+retSqlTab("SA1")+" on (A1_FILIAL = '"+xFilial("SA1")+"' and A1_COD = AF8_CLIENT and A1_LOJA = AF8_LOJA and SA1.D_E_L_E_T_ = ' ') "
	cQuery += "where "
	cQuery += "AF8_FILIAL = '"+xFilial("AF8")+"' "
	IF !empty(::RESOURCE)
		cQuery += "and AE8_RECURS = '"+::RESOURCE+"' "
	endif
	cQuery += "and AE8_ATIVO = '1' "
	cQuery += "and AE8.D_E_L_E_T_ = ' ' "
	cQuery += "order by AE8_FILIAL, AE8_RECURS, ZN0_DATA, ZN0_PROJET, ZN0_TAREFA"

	dbUseArea(.T.,"TOPCONN",TCGenQry(,,cQuery),"QRYAGENDA",.T.,.T.)

	dbSelectArea("QRYAGENDA")
	QRYAGENDA->(DBGOTOP())

	while QRYAGENDA->(!eof())
		oDadosAgenda := WSClassNew("DadosAgenda")
	
		oDadosAgenda:RESOURCE	:= QRYAGENDA->ZN0_RECURS
		oDadosAgenda:CUSTOMER	:= QRYAGENDA->(AF8_CLIENT+AF8_LOJA)
		oDadosAgenda:PROJDESC	:= alltrim(QRYAGENDA->AF8_DESCRI)
		oDadosAgenda:TASKDESC	:= alltrim(QRYAGENDA->AF9_DESCRI)
		oDadosAgenda:CUSTNAME	:= alltrim(QRYAGENDA->A1_NREDUZ)
		oDadosAgenda:RESONAME	:= alltrim(QRYAGENDA->AE8_DESCRI)

		if QRYAGENDA->ZN0_RECNOS<=0
			oDadosAgenda:PROJCODE	:= QRYAGENDA->ZN0_PROJET
			oDadosAgenda:PROJTASK	:= QRYAGENDA->ZN0_TAREFA
			oDadosAgenda:DATESCHE	:= QRYAGENDA->ZN0_DATA
			oDadosAgenda:TIMESTAR	:= QRYAGENDA->ZN0_HORAI
			oDadosAgenda:TIMEEND		:= QRYAGENDA->ZN0_HORAF
			oDadosAgenda:TIMEDESC	:= IIF(EMPTY(QRYAGENDA->ZN0_OUTROS),"01:00",QRYAGENDA->ZN0_OUTROS)
		else
			AFU->(dbGoTo(QRYAGENDA->ZN0_RECNOS))
			oDadosAgenda:PROJCODE	:= AFU->AFU_PROJET
			oDadosAgenda:PROJTASK	:= AFU->AFU_TAREFA
			oDadosAgenda:DATESCHE	:= dtos(AFU->AFU_DATA)
			oDadosAgenda:TIMESTAR	:= AFU->AFU_HORAI
			oDadosAgenda:TIMEEND		:= AFU->AFU_HORAF
			oDadosAgenda:TIMEDESC	:= AFU->AFU_ZDESCH
			oDadosAgenda:VLRALMO		:= AFU->AFU_VLRALM
			oDadosAgenda:VLRDESP		:= AFU->AFU_VALDES
			oDadosAgenda:OBSDESP		:= AFU->AFU_OBSDSP
			oDadosAgenda:DESCRIPT	:= MSMM(AFU->AFU_CODMEM,80)
		endif
		oDadosAgenda:OSGERADA	:= QRYAGENDA->ZN0_GERADA
		oDadosAgenda:AGERECNO	:= QRYAGENDA->ZN0_RECNO
		oDadosAgenda:OSRECNO		:= QRYAGENDA->ZN0_RECNOS
			
		aAdd(::RESOSCHED,oDadosAgenda)
		QRYAGENDA->(dbSkip())
	enddo

	dbSelectArea("QRYAGENDA"); dbCloseArea()
return(lRet)

//METODO PARA APONTAMENTO DE TAREFAS
WSMETHOD PUTJOB WSRECEIVE TOKEN,JOBUPDT WSSEND OSMESSAGE WSSERVICE DTRWEBSR
	local lRet := .t.
	local cCC 	:= "peterson@dataroute.com.br , ricardo@dataroute.com.br"
	LOCAL cAct	:= "[Inclusao] DATAROUTE - Ordem de Servico"
	local cCaminho:="\workflow\"

	::OSMESSAGE	:= ""

	//VALIDA TOKEN PARA USO DO WS
	if !(::TOKEN = "DATAROUTEWEB")
		SetSoapFault("Acesso nao autorizado",;
			"Verifique os parametros informados.")
		return .F.
	endif
	
	//VALIDA CADASTRO DE RECURSO
	dbSelectArea("AE8")
	AE8->(dbSetOrder(1))
	AE8->(dbSeek(xFilial("AE8")+ALLTRIM(::JOBUPDT:RESOURCE)))
	IF ALLTRIM(AE8->AE8_RECURS) <> ALLTRIM(::JOBUPDT:RESOURCE)
		SetSoapFault("Recurso nao encontrado",;
			"Verifique os parametros informados.")
		return .F.
	endif
	
	if AE8->AE8_ATIVO == '2'
		SetSoapFault("Recurso bloqueado",;
			"Verifique os parametros informados.")
		return .F.
	ENDIF
	
	//VALIDACAO DO PROJETO e TAREFA
	dbSelectArea("AF8")
	AF8->(dbSetOrder(1))
	AF8->(dbSeek(xFilial("AF8")+::JOBUPDT:PROJCODE))
	IF ALLTRIM(AF8->AF8_PROJET) <> ALLTRIM(::JOBUPDT:PROJCODE)
		SetSoapFault("Projeto nao encontrado",;
			"Verifique os parametros informados.")
		return .F.
	endif

	IF ALLTRIM(AF8->AF8_FASE) <> "03"
		SetSoapFault("Fase do projeto nao esta em execucao",;
			"Verifique os parametros informados.")
		return .F.
	endif

	dbSelectArea("AF9")
	AF9->(dbSetOrder(1))
	AF9->(dbSeek(xFilial("AF9")+AF8->AF8_PROJET+AF8->AF8_REVISA+alltrim(::JOBUPDT:PROJTASK)))
	if ALLTRIM(AF9->AF9_TAREFA) <> ALLTRIM(::JOBUPDT:PROJTASK)
		SetSoapFault("Tarefa nao encontrada",;
			"Verifique os parametros informados.")
		return .F.
	endif

	//VALIDAR CAMPOS HORA
	IF substr(::JOBUPDT:TIMESTAR,3,1)<>":";
			.or. substr(::JOBUPDT:TIMEEND,3,1)<>":";
			.or. substr(::JOBUPDT:TIMEDESC,3,1)<>":"
		SetSoapFault("Campos de horarios estao desconfigurados devem ser no formato: 99:99",;
			"Verifique os parametros informados.")
		return .F.
	endif
	
	//VALIDAR DATA INFORMADA
	IF empty(::JOBUPDT:DATESCHE).or.;
			substr(::JOBUPDT:DATESCHE,3,1)<>"/".or.;
			substr(::JOBUPDT:DATESCHE,6,1)<>"/"
		
		SetSoapFault("Informe corretamente a data do atendimento (DD/MM/AA)",;
			"Verifique os parametros informados.")
		return .F.
	endif

	//VALIDAR TAREFA JA APONTADA
	dbSelectArea("AFU")
	AFU->(dbSetOrder(1))
	AFU->(dbSeek(xFilial("AFU")+"1"+AF8->AF8_PROJET+AF8->AF8_REVISA+AF9->AF9_TAREFA+AE8->AE8_RECURS+dtos(ctod(::JOBUPDT:DATESCHE))))

	IF AFU->AFU_PROJET+AFU->AFU_REVISA+AFU->AFU_TAREFA+AFU->AFU_RECURS+AFU->AFU_HORAI == ;
			AF8->AF8_PROJET+AF8->AF8_REVISA+AF9->AF9_TAREFA+AE8->AE8_RECURS+::JOBUPDT:TIMESTAR
		
		SetSoapFault("OS ja apontada para esta tarefa e horario inicial",;
			"Verifique os parametros informados.")
		return .F.
	endif

	//GRAVACAO DO APONTAMENTO
	begin Transaction
		recLock("AFU",.T.)
		AFU->AFU_FILIAL	:= xFilial("AFU")
		AFU->AFU_RECURS	:= ::JOBUPDT:RESOURCE
		AFU->AFU_PROJET	:= ::JOBUPDT:PROJCODE
		AFU->AFU_REVISA	:= AF8->AF8_REVISA
		AFU->AFU_TAREFA	:= ::JOBUPDT:PROJTASK
		AFU->AFU_DATA		:= ctod(::JOBUPDT:DATESCHE)
		AFU->AFU_HORAI	:= ::JOBUPDT:TIMESTAR
		AFU->AFU_HORAF	:= ::JOBUPDT:TIMEEND
		AFU->AFU_ZDESCH	:= ::JOBUPDT:TIMEDESC
		AFU->AFU_HQUANT	:= u_PMSTimeDiff(AFU->AFU_HORAF,AFU->AFU_HORAI,,AFU->AFU_ZDESCH)
		AFU->AFU_NUMSEQ	:= ""
		AFU->AFU_VLRALM	:= ::JOBUPDT:VLRALMO
		AFU->AFU_VALDES	:= ::JOBUPDT:VLRDESP
		AFU->AFU_OBSDSP	:= FwNoAccent(::JOBUPDT:OBSDESP)
		AFU->AFU_CTRRVS	:= "1"
		AFU->AFU_TPREAL	:= "4"
		AFU->AFU_TPHORA	:= "1"
		msUnlock()
		//grava campo memo
		//MSMM(,TamSx3("AFU_OBS")[1],,u_RemAcento(::JOBUPDT:DESCRIPT),1,,,"AFU","AFU_CODMEM")
		
		conout("=========== texto da OS ==============")
		conout(::JOBUPDT:DESCRIPT)
		conout("--------------------------------------")
		conout(FwNoAccent(::JOBUPDT:DESCRIPT))
		conout("======================================")
		MSMM(,TamSx3("AFU_OBS")[1],,FwNoAccent(::JOBUPDT:DESCRIPT),1,,,"AFU","AFU_CODMEM")
		//
		//INSERCAO DE DESPESAS
		//		
		//ALMOCO

		dbSelectArea("AJC")
		AJC->(dbSetOrder(3))//AJC_FILIAL+AJC_RECURS+AJC_DATA+AJC_PROJET+AJC_REVISA+AJC_TAREFA
		cChave := AFU->AFU_RECURS+;
			dtoS(AFU->AFU_DATA)+;
			AFU->AFU_PROJET+AFU->AFU_REVISA+;
			AFU->AFU_TAREFA
			
		IF !AJC->(dbSeek(xFilial("AJC")+cChave+"0001"))
		
			if AFU->AFU_VLRALM >0
				recLock("AJC",.T.)
				AJC->AJC_FILIAL	:= xFilial("AJC")
				AJC->AJC_PROJET	:= AFU->AFU_PROJET
				AJC->AJC_REVISA	:= AFU->AFU_REVISA
				AJC->AJC_TAREFA	:= AFU->AFU_TAREFA
				AJC->AJC_RECURS	:= AFU->AFU_RECURS
				AJC->AJC_DATA		:= AFU->AFU_DATA
				AJC->AJC_TIPOD	:= "0001"
				AJC->AJC_TIPO		:= "2"//DESPESAS
				AJC->AJC_CTRRVS	:=	"1"
				AJC->AJC_OBSDSP	:= AFU->AFU_OBSDSP
				
				AJC->AJC_CUSTO1	:= AFU->AFU_VLRALM
				msUnlock()
			endif
		ENDIF
		
		//DESLOCAMENTO
		IF !AJC->(dbSeek(xFilial("AJC")+cChave+"0002"))
			if AFU->AFU_VALDES > 0
				recLock("AJC",.T.)
				AJC->AJC_FILIAL	:= xFilial("AJC")
				AJC->AJC_PROJET	:= AFU->AFU_PROJET
				AJC->AJC_REVISA	:= AFU->AFU_REVISA
				AJC->AJC_TAREFA	:= AFU->AFU_TAREFA
				AJC->AJC_RECURS	:= AFU->AFU_RECURS
				AJC->AJC_DATA		:= AFU->AFU_DATA
				AJC->AJC_TIPO		:= "1"//PRODUTO
				AJC->AJC_CTRRVS	:=	"1"
				AJC->AJC_COD		:= "02001"
				AJC->AJC_OBSDSP	:= AFU->AFU_OBSDSP
				AJC->AJC_QUANT	:= AFU->AFU_VALDES
				AJC->AJC_CUSTO1	:= AJC->AJC_QUANT * superGetMV("DT_VLXKM",,0.50)
				msUnlock()
			endif
		ENDIF

		//ATUALIZA A AGENDA COMO GERADA
		if ::JOBUPDT:AGERECNO > 0
			ZN0->(dbGoTo(::JOBUPDT:AGERECNO))
			recLock("ZN0")
			ZN0->ZN0_GERADA	:= "S"
			ZN0->ZN0_RECNOS			:= AFU->(recno())
			msUnLock()
		endif
	end Transaction
	
	//WORKFLOW
	oProcess := TWFProcess():New("Ordem de Servico")
	oProcess:NewTask("DTR44A02-1",cCaminho+"apontamento.html")
	oHtml := oProcess:oHTML
	
	//Funcao que envia e-mail para o usuario
	cAssunto      := cAct

	oProcess:cSubject := cAssunto   // Assunto do E-Mail
	
	//DESTINATARIOS DO E-MAIL
	//CONSULTOR
	oProcess:cTo:= ALLTRIM(AE8->AE8_EMAIL)
	
	//CLIENTE
	if AF8->AF8_ZENVMA == "1"
		oProcess:cTo:= ALLTRIM(AF8->AF8_ZEMAIL)+", "+ALLTRIM(AE8->AE8_EMAIL)
		oProcess:oHTML:ValByName("CLINOME","Prezado <strong>"+ALLTRIM(AF8->AF8_ZNRESP)+"</strong>, estamos enviando o posicionamento das atividades realizadas, abaixo os dados registrados em nosso sistema.")
	ELSE
		oProcess:oHTML:ValByName("CLINOME","")
	endif
	oProcess:cCC := cCC

	oProcess:oHTML:ValByName("PROJETO",ALLTRIM(AF8->AF8_DESCRI))
	oProcess:oHTML:ValByName("CONSULTOR",ALLTRIM(AE8->AE8_DESCRI))
	oProcess:oHTML:ValByName("DATA",dtoc(AFU->AFU_DATA))
	oProcess:oHTML:ValByName("HINI",AFU->AFU_HORAI)
	oProcess:oHTML:ValByName("HFIM",AFU->AFU_HORAF)
	oProcess:oHTML:ValByName("DESC",AFU->AFU_ZDESCH)
	oProcess:oHTML:ValByName("TOTAL",TRANSFORM(AFU->AFU_HQUANT,pesqPict("AFU","AFU_HQUANT")))
	
	AAdd((oProcess:oHTML:ValByName("det.atividade")),"Tarefa: "+alltrim(AF9->AF9_TAREFA)+"-"+alltrim(AF9->AF9_DESCRI)+": <br>"+MSMM(AFU->AFU_CODMEM,80))
	
	//Anexo Logo
	oProcess:AttachFile("\workflow\logo_dataroute.png")
	
	//ENVIO DA OS POR E-MAIL
	oProcess:Start()
	
	//Finalizando o Processo.
	oProcess:Finish()
	
	::OSMESSAGE	:= "OS gerada e e-mail enviado."
return(lRet)

//METODO PARA EXCLUIR APONTAMENTO DE TAREFAS
WSMETHOD DELJOB WSRECEIVE TOKEN,JOBUPDT WSSEND OSMESSAGE WSSERVICE DTRWEBSR
	local lRet := .t.
	local cCC 	:= "peterson@dataroute.com.br , ricardo@dataroute.com.br"
	LOCAL cAct	:= "[Exclusao] DATAROUTE - Ordem de Servico"
	local cCaminho:="\workflow\"

	::OSMESSAGE	:= ""

	//VALIDA TOKEN PARA USO DO WS
	if !(::TOKEN = "DATAROUTEWEB")
		SetSoapFault("Acesso nao autorizado",;
			"Verifique os parametros informados.")
		return .F.
	endif
	
	//VALIDA CADASTRO DE RECURSO
	dbSelectArea("AE8")
	AE8->(dbSetOrder(1))
	AE8->(dbSeek(xFilial("AE8")+ALLTRIM(::JOBUPDT:RESOURCE)))
	IF ALLTRIM(AE8->AE8_RECURS) <> ALLTRIM(::JOBUPDT:RESOURCE)
		SetSoapFault("Recurso nao encontrado",;
			"Verifique os parametros informados.")
		return .F.
	endif
	
	if AE8->AE8_ATIVO == '2'
		SetSoapFault("Recurso bloqueado",;
			"Verifique os parametros informados.")
		return .F.
	ENDIF
	
	//VALIDACAO DO PROJETO e TAREFA
	dbSelectArea("AF8")
	AF8->(dbSetOrder(1))
	AF8->(dbSeek(xFilial("AF8")+::JOBUPDT:PROJCODE))
	IF ALLTRIM(AF8->AF8_PROJET) <> ALLTRIM(::JOBUPDT:PROJCODE)
		SetSoapFault("Projeto nao encontrado",;
			"Verifique os parametros informados.")
		return .F.
	endif

	IF ALLTRIM(AF8->AF8_FASE) <> "03"
		SetSoapFault("Fase do projeto nao esta em execucao",;
			"Verifique os parametros informados.")
		return .F.
	endif

	dbSelectArea("AF9")
	AF9->(dbSetOrder(1))
	AF9->(dbSeek(xFilial("AF9")+AF8->AF8_PROJET+AF8->AF8_REVISA+alltrim(::JOBUPDT:PROJTASK)))
	if ALLTRIM(AF9->AF9_TAREFA) <> ALLTRIM(::JOBUPDT:PROJTASK)
		SetSoapFault("Tarefa nao encontrada",;
			"Verifique os parametros informados.")
		return .F.
	endif

	//VALIDAR CAMPOS HORA
	IF substr(::JOBUPDT:TIMESTAR,3,1)<>":";
			.or. substr(::JOBUPDT:TIMEEND,3,1)<>":";
			.or. substr(::JOBUPDT:TIMEDESC,3,1)<>":"
		SetSoapFault("Campos de horarios estao desconfigurados devem ser no formato: 99:99",;
			"Verifique os parametros informados.")
		return .F.
	endif
	
	//VALIDAR DATA INFORMADA
	IF empty(::JOBUPDT:DATESCHE).or.;
			substr(::JOBUPDT:DATESCHE,3,1)<>"/".or.;
			substr(::JOBUPDT:DATESCHE,6,1)<>"/"
		
		SetSoapFault("Informe corretamente a data do atendimento (DD/MM/AA)",;
			"Verifique os parametros informados.")
		return .F.
	endif

	//VALIDAR TAREFA JA APONTADA
	dbSelectArea("AFU")
	AFU->(dbSetOrder(1))
	AFU->(dbSeek(xFilial("AFU")+"1"+AF8->AF8_PROJET+AF8->AF8_REVISA+AF9->AF9_TAREFA+AE8->AE8_RECURS+dtos(ctod(::JOBUPDT:DATESCHE))))

	IF AFU->AFU_PROJET+AFU->AFU_REVISA+AFU->AFU_TAREFA+AFU->AFU_RECURS+AFU->AFU_HORAI <> ;
			AF8->AF8_PROJET+AF8->AF8_REVISA+AF9->AF9_TAREFA+AE8->AE8_RECURS+::JOBUPDT:TIMESTAR
		
		SetSoapFault("OS nao encontrada",;
			"Verifique os parametros informados.")
		return .F.
	endif

	//APAGAR DO APONTAMENTO
	begin Transaction
		cChave := AFU->AFU_RECURS+;
			dtoS(AFU->AFU_DATA)+;
			AFU->AFU_PROJET+AFU->AFU_REVISA+;
			AFU->AFU_TAREFA
		
		cTxtOS := MSMM(AFU->AFU_CODMEM,80)

		//WORKFLOW
		oProcess := TWFProcess():New("Ordem de Servico")
		oProcess:NewTask("DTR44A02-1",cCaminho+"apontamento.html")
		oHtml := oProcess:oHTML
		
		//Funcao que envia e-mail para o usuario
		cAssunto      := cAct
	
		oProcess:cSubject := cAssunto   // Assunto do E-Mail
		
		//DESTINATARIOS DO E-MAIL
		//CONSULTOR
		oProcess:cTo:= ALLTRIM(AE8->AE8_EMAIL)
		
		//CLIENTE
		if AF8->AF8_ZENVMA == "1"
			oProcess:cTo:= ALLTRIM(AF8->AF8_ZEMAIL)+", "+ALLTRIM(AE8->AE8_EMAIL)
			oProcess:oHTML:ValByName("CLINOME","Prezado <strong>"+ALLTRIM(AF8->AF8_ZNRESP)+"</strong>, estamos enviando o posicionamento das atividades realizadas, abaixo os dados registrados em nosso sistema.")
		ELSE
			oProcess:oHTML:ValByName("CLINOME","")
		endif
		oProcess:cCC := cCC
	
		oProcess:oHTML:ValByName("PROJETO",ALLTRIM(AF8->AF8_DESCRI))
		oProcess:oHTML:ValByName("CONSULTOR",ALLTRIM(AE8->AE8_DESCRI))
		oProcess:oHTML:ValByName("DATA",dtoc(AFU->AFU_DATA))
		oProcess:oHTML:ValByName("HINI",AFU->AFU_HORAI)
		oProcess:oHTML:ValByName("HFIM",AFU->AFU_HORAF)
		oProcess:oHTML:ValByName("DESC",AFU->AFU_ZDESCH)
		oProcess:oHTML:ValByName("TOTAL",TRANSFORM(AFU->AFU_HQUANT,pesqPict("AFU","AFU_HQUANT")))
		
		AAdd((oProcess:oHTML:ValByName("det.atividade")),"Tarefa: "+alltrim(AF9->AF9_TAREFA)+"-"+alltrim(AF9->AF9_DESCRI)+": <br>"+cTxtOS)
		
		//Anexo Logo
		oProcess:AttachFile("\workflow\logo_dataroute.png")

		recLock("AFU",.F.)
		dbDelete()
		msUnLock()
		
		//
		//APAGAR DESPESAS
		//		
		//ALMOCO

		dbSelectArea("AJC")
		AJC->(dbSetOrder(3))//AJC_FILIAL+AJC_RECURS+AJC_DATA+AJC_PROJET+AJC_REVISA+AJC_TAREFA
			
		IF AJC->(dbSeek(xFilial("AJC")+cChave+"0001"))
		
			if AFU->AFU_VLRALM >0
				recLock("AJC",.F.)
				dbDelete()
				msUnlock()
			endif
		ENDIF
		
		//DESLOCAMENTO
		IF AJC->(dbSeek(xFilial("AJC")+cChave+"0002"))
			if AFU->AFU_VALDES > 0
				recLock("AJC",.F.)
				dbDelete()
				msUnlock()
			endif
		ENDIF

		//ATUALIZA A AGENDA COMO GERADA
		if ::JOBUPDT:AGERECNO > 0
			ZN0->(dbGoTo(::JOBUPDT:AGERECNO))
			recLock("ZN0")
			ZN0->ZN0_GERADA	:= " "
			ZN0->ZN0_RECNOS	:= 0
			msUnLock()
		endif
	end Transaction
	
	//ENVIO DA OS POR E-MAIL
	oProcess:Start()
	
	//Finalizando o Processo.
	oProcess:Finish()
	
	::OSMESSAGE	:= "OS gerada e e-mail enviado."
return(lRet)

//RESUMO DE HORAS
WSMETHOD GETRESUMO WSRECEIVE TOKEN,CODRESOURSE,DateStart WSSEND RESUMOHS WSSERVICE DTRWEBSR

	Local oBL		:= DTR44A04_BL():New()
	local aLstItens := {}
	local nTotHr	:= 0

	//VALIDA TOKEN PARA USO DO WS
	if !(::TOKEN = "DATAROUTEWEB")
		SetSoapFault("Acesso nao autorizado",;
			"Verifique os parametros informados.")
		return .F.
	endif

	aLstItens := oBL:getItensRec(::CODRESOURSE,ctod(::DateStart),.T.)
	
	For nX := 1 To Len(aLstItens)
		
		oResumo := WSClassNew("ResumOS")

		nTotHr += aLstItens[nX][7]

		cProjet	:= AllTrim(POSICIONE("AF8",1,xFilial("AF8")+aLstItens[nX][2],"AF8_DESCRI"))
		cTarefa	:= AllTrim(POSICIONE("AF9",1,xFilial("AF9")+aLstItens[nX][2],"AF9_DESCRI"))


		oResumo:DATA		:= aLstItens[nX][1]
		oResumo:PROJETO	:= aLstItens[nX][2]+" - "+cProjet
		oResumo:TAREFA	:= aLstItens[nX][3]+" - "+cTarefa
		oResumo:HORAINI	:= aLstItens[nX][4]
		oResumo:HORAFIM	:= aLstItens[nX][5]
		oResumo:OUTROS	:= aLstItens[nX][6]
		oResumo:TOTAL		:= Transform(aLstItens[nX][7],PesqPict("AFU","AFU_HQUANT"))
			
		AAdd(RESUMOHS:APTOS,oResumo)
			
	Next
	RESUMOHS:nTotal	:= nTotHr
return(.T.)
